import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosRequestHeaders } from 'axios'
import { Message, Notification } from '@arco-design/web-vue'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import { getNowDate, getRemainderTime } from '@/utils/myUtils'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

interface ICodeMessage {
  [propName: number]: string
}

const StatusCodeMessage: ICodeMessage = {
  200: '服务器成功返回请求的数据',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）',
  204: '删除数据成功',
  400: '请求错误(400)',
  401: '未授权，请重新登录(401)',
  403: '拒绝访问(403)',
  404: '请求出错(404)',
  408: '请求超时(408)',
  500: '服务器错误(500)',
  501: '服务未实现(501)',
  502: '网络错误(502)',
  503: '服务不可用(503)',
  504: '网络超时(504)'
}

const http: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 30 * 1000
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 进度条
    NProgress.start()
    config.headers = {
      'Content-Type': 'application/json;charset=UTF-8' // 配置请求头
    }

    let token = localStorage.getItem('accessToken')
    console.log(token)
    let tokenSetTime = localStorage.getItem('tokenSetTime')
    // console.log(tokenSetTime)

    if (token == '' || token == null || token == undefined) {
      localStorage.removeItem('token')
      // router.replace('/login')
    }

    // console.log(getRemainderTime(tokenSetTime))
    // if (getRemainderTime(tokenSetTime)[3] >= 1) {
    // } else {

    // }
    // localStorage.removeItem('token')
    // localStorage.removeItem('accessToken')
    // localStorage.removeItem('tokenSetTime')

    if (tokenSetTime != null && tokenSetTime != undefined) {
      if (getRemainderTime(tokenSetTime)[3] < 2 && token != null && token != undefined) {
        let userInfo = JSON.parse(localStorage.getItem('userInfo'))
        config.headers['accessToken'] = token
        if (userInfo != null) {
          config.headers['platFormUserId'] = 1
        }
      } else {
        Message.error('登录已过期，请重新登录！')
        localStorage.removeItem('token')
        localStorage.removeItem('tokenSetTime')
        localStorage.removeItem('accessToken')
        router.replace('/login')
      }
    } else {
      router.replace('/login')
    }

    // let userInfo = JSON.parse(localStorage.getItem('userInfo'))
    // config.headers['accessToken'] = token
    // if (userInfo != null) {
    //   config.headers['platFormUserId'] = 1
    // }

    // console.log(platFormUserId)

    // 获取token
    // const token = getToken()
    // console.log(token)

    // 判断有无token
    // if (token) {
    //   // 如果没有请求头，就赋空对象
    //   if (!config.headers) {
    //     config.headers = {}
    //   }
    // 将拿到的token添加到请求头当中去
    // config.headers.common['Authorization'] = `Bearer ${localStorage.getItem('accessToken')}`
    // console.log(config.headers)

    // config.headers['Access-Control-Allow-Origin'] = '*'

    // }
    // 将config返回出去
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    //console.log(response)
    const { data } = response
    const { msg, result, status } = data

    if (msg == 'accessToken 错误') {
      router.replace('/login')
    }
    // token失效
    // if (status === 401) {
    //   NProgress.done()
    //   // Message.error('token失效')
    //   router.replace('/login')
    //   return Promise.reject(new Error('token失效'))
    // }
    //console.log(result);

    // if (!result) {
    //   NProgress.done()
    //console.log(msg);

    // 如果错误信息长度过长，使用 Notification 进行提示
    // if (msg.length <= 2000000100) {
    //   Message.error(msg || '服务器端错误')
    // } else {
    //   Notification.error(msg || '服务器端错误')
    // }
    //   return Promise.reject(new Error('Error'))
    // }
    NProgress.done()
    //console.log(response)
    return response
  },
  (error) => {
    //console.log(111)
    NProgress.done()
    Message.clear()
    const response = Object.assign({}, error.response)
    // response && Message.error(StatusCodeMessage[response.status] || '系统异常, 请检查网络或联系管理员！')
    return Promise.reject(error)
  }
)

const request = <T = unknown>(config: AxiosRequestConfig): Promise<ApiRes<T>> => {
  return new Promise((resolve, reject) => {
    http
      .request<T>(config)
      .then((res: AxiosResponse) => resolve(res.data))
      .catch((err: { message: string }) => reject(err))
  })
}

request.get = <T = any>(url: string, params?: object, headers?: AxiosRequestHeaders): Promise<ApiRes<T>> => {
  return request({
    method: 'get',
    url,
    params,
    headers
  })
}

request.post = <T = any>(url: string, params?: object, headers?: AxiosRequestHeaders): Promise<ApiRes<T>> => {
  return request({
    method: 'post',
    url,
    data: params,
    headers
  })
}

export default request
